﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Scheduler.Model;
using Scheduler.Common.Helper;

namespace Scheduler.WebAPI
{
    /// <summary>
    /// 自定义的错误处理过滤器
    /// </summary>
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<ExceptionFilter> _logger;
        private IHostEnvironment _environment;

        public ExceptionFilter(ILogger<ExceptionFilter> logger, IHostEnvironment environment)
        {

            _logger = logger;
            _environment = environment;
        }
        public void OnException(ExceptionContext context)
        { 
            Exception ex = context.Exception;
            string errorMsg = $"错误消息:{ex.Message}{Environment.NewLine}错误追踪:{ex.StackTrace}";
            //LoggerHelper.Logger.Error(errorMsg);
            string message = _environment.IsDevelopment() ? ex.Message : "抱歉，服务端出错了";
            var errorResult = MessageModel<object>.ErrorResult(message);
            _logger.LogError(errorMsg);
            var objectResult = new ObjectResult(errorResult);
            objectResult.StatusCode = 500;
            context.Result = objectResult;
            context.ExceptionHandled = true;
        }
    }
}
